<template>
  <div class="workload-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="search-bar">
        <el-form :model="searchForm" inline>
          <el-form-item v-if="activeTab === 'operator'" label="真实姓名">
            <el-input 
              v-model="searchForm.realName" 
              placeholder="请输入真实姓名" 
              clearable 
              @keyup.enter="handleSearch"
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item v-if="activeTab === 'operator'" label="工号">
            <el-input 
              v-model="searchForm.opNum" 
              placeholder="请输入工号" 
              clearable 
              @keyup.enter="handleSearch"
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item v-if="activeTab === 'barcode'" label="条码号">
            <el-input 
              v-model="searchForm.barCode" 
              placeholder="请输入条码号" 
              clearable 
              @keyup.enter="handleSearch"
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 350px;"
              :editable="false"
              :clearable="true"
              :class="{ 'no-auto-focus': !isInitialized }"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              🔍 搜索
            </el-button>
            <el-button @click="handleReset">
              🔄 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 主体内容区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">📊 工作量管理</span>
          <div class="header-actions">
            <div class="record-stats">
              <el-tag type="info">共 {{ total }} 条记录</el-tag>
            </div>
          </div>
        </div>
      </template>
      
      <!-- Tab 切换 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="workload-tabs">
        <el-tab-pane label="📋 操作员测量统计" name="operator">
          <div class="table-container">
            <el-table 
              :data="tableData" 
              style="width: 100%" 
              v-loading="loading"
              :height="tableHeight"
              class="custom-table"
            >
              <el-table-column prop="opNum" label="工号" width="150" show-overflow-tooltip />
              <el-table-column prop="realName" label="真实姓名" width="200" show-overflow-tooltip />
              <el-table-column prop="blNum" label="测量次数" width="150" align="center">
                <template #default="{ row }">
                  <el-tag type="primary" size="large">{{ row.blNum }}</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="🏷️ 条码测量统计" name="barcode">
          <div class="table-container">
            <el-table 
              :data="tableData" 
              style="width: 100%" 
              v-loading="loading"
              :height="tableHeight"
              class="custom-table"
            >
              <el-table-column prop="barCode" label="条码号" width="200" show-overflow-tooltip />
              <el-table-column prop="blNum" label="测量次数" width="150" align="center">
                <template #default="{ row }">
                  <el-tag type="success" size="large">{{ row.blNum }}</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pageCurrent"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { countBlNum, countBarCode } from '../api/business.js'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const pageSize = ref(10)
const pageCurrent = ref(1)
const activeTab = ref('operator')

// 获取当天的开始和结束时间
const getTodayRange = () => {
  const today = new Date()
  const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0)
  const endOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59)
  
  const formatDateTime = (date) => {
    return date.getFullYear() + '-' + 
           String(date.getMonth() + 1).padStart(2, '0') + '-' + 
           String(date.getDate()).padStart(2, '0') + ' ' + 
           String(date.getHours()).padStart(2, '0') + ':' + 
           String(date.getMinutes()).padStart(2, '0') + ':' + 
           String(date.getSeconds()).padStart(2, '0')
  }
  
  return [formatDateTime(startOfDay), formatDateTime(endOfDay)]
}

// 搜索表单 - 初始时不设置时间范围，避免自动聚焦
const searchForm = reactive({
  realName: '',
  opNum: '',
  barCode: '',
  timeRange: []
})

// 初始化标志
const isInitialized = ref(false)

// 初始化时间范围
const initializeTimeRange = () => {
  // 延迟设置时间范围，避免自动聚焦
  setTimeout(() => {
    if (!isInitialized.value) {
      searchForm.timeRange = getTodayRange()
      isInitialized.value = true
    }
  }, 500)
}

// 加载管理器
let loadingInstance = null
const showLoading = (text = '加载中...') => {
  if (loadingInstance) {
    loadingInstance.close()
  }
  loadingInstance = ElLoading.service({
    lock: true,
    text: text,
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

const hideLoading = () => {
  if (loadingInstance) {
    loadingInstance.close()
    loadingInstance = null
  }
}

// 计算表格高度
const tableHeight = computed(() => {
  return 'calc(100vh - 380px)'
})

// 获取数据
const getData = async () => {
  loading.value = true
  
  try {
    const params = {
      pageNum: pageCurrent.value,
      pageSize: pageSize.value
    }
    
    // 根据当前tab添加不同的搜索参数
    if (activeTab.value === 'operator') {
      // 操作员测量统计
      if (searchForm.realName) {
        params.realName = searchForm.realName
      }
      if (searchForm.opNum) {
        params.opNum = searchForm.opNum
      }
    } else {
      // 条码测量统计
      if (searchForm.barCode) {
        params.barCode = searchForm.barCode
      }
    }
    
    // 处理时间范围
    if (searchForm.timeRange && searchForm.timeRange.length === 2) {
      params.startTime = searchForm.timeRange[0]
      params.endTime = searchForm.timeRange[1]
    }
    
    let res
    if (activeTab.value === 'operator') {
      res = await countBlNum(params)
    } else {
      res = await countBarCode(params)
    }
    
    console.info('工作量统计数据:', res)
    
    if (res && res.success === true && res.content) {
      // 处理分页数据结构
      tableData.value = res.content.records || []
      total.value = res.content.total || 0
      
      ElMessage.success(`📊 成功获取${tableData.value.length}条记录`)
    } else {
      throw new Error(res?.message || '数据格式错误')
    }
  } catch (error) {
    console.error('获取工作量统计失败:', error)
    ElMessage.error(error.data?.message || '获取工作量统计失败')
  } finally {
    loading.value = false
  }
}

// Tab切换处理
const handleTabChange = (tabName) => {
  activeTab.value = tabName
  // 清空搜索条件，但保持默认时间范围
  searchForm.realName = ''
  searchForm.opNum = ''
  searchForm.barCode = ''
  searchForm.timeRange = getTodayRange()
  pageCurrent.value = 1
  getData()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  getData()
}

const handleCurrentChange = (page) => {
  pageCurrent.value = page
  getData()
}

// 搜索处理
const handleSearch = () => {
  pageCurrent.value = 1
  getData()
}

const handleReset = () => {
  searchForm.realName = ''
  searchForm.opNum = ''
  searchForm.barCode = ''
  searchForm.timeRange = getTodayRange()
  pageCurrent.value = 1
  getData()
}

// 组件挂载时初始化
onMounted(() => {
  initializeTimeRange()
  getData()
})
</script>

<style scoped>
.workload-management {
  background: #f5f7fa;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-bar {
  display: flex;
  align-items: center;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  padding-bottom: 70px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.card-title {
  font-size: 18px;
  font-weight: 700;
  color: #1e40af;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.record-stats {
  display: flex;
  align-items: center;
  gap: 8px;
}

.workload-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-tabs__content) {
  flex: 1;
  overflow: hidden;
}

:deep(.el-tab-pane) {
  height: 100%;
  overflow: hidden;
}

.table-container {
  flex: 1;
  overflow: hidden;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.custom-table {
  width: 100%;
  flex: 1;
}

.pagination {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  background: #ffffff;
  border-top: 1px solid #e4e7ed;
  z-index: 10;
}

/* 表格滚动条样式 */
:deep(.el-table) {
  height: 100% !important;
}

:deep(.el-table__body-wrapper) {
  /* 只在需要时显示滚动条 */
  overflow-y: auto !important;
  overflow-x: hidden !important;
  max-height: calc(100vh - 450px) !important;
  /* 为底部分页器预留更多空间，避免遮挡 */
  padding-bottom: 10px !important;
}

/* 滚动条样式优化 */
:deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 8px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f5f5f5;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
  transition: background 0.3s ease;
  min-height: 20px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-corner {
  background: #f5f5f5;
}

/* 表格横向铺满 */
:deep(.el-table) {
  width: 100% !important;
  min-width: 100% !important;
}

:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__footer-wrapper) {
  width: 100% !important;
}

/* 确保表格内容不会超出容器 */
:deep(.el-table__header),
:deep(.el-table__body) {
  width: 100% !important;
  table-layout: fixed;
}

/* 表格单元格内容溢出处理 */
:deep(.el-table .cell) {
  word-break: break-word;
  word-wrap: break-word;
  white-space: normal;
  line-height: 1.4;
}

/* 确保最后一行数据不被遮挡 */
:deep(.el-table__body tr:last-child td) {
  border-bottom: 1px solid #ebeef5;
}

/* Tab样式优化 */
:deep(.el-tabs__header) {
  margin-bottom: 16px;
}

:deep(.el-tabs__nav-wrap) {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 4px;
}

:deep(.el-tabs__item) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-tabs__item.is-active) {
  background: #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 防止日期选择器自动聚焦 */
.no-auto-focus :deep(.el-input__wrapper) {
  pointer-events: none;
}

.no-auto-focus :deep(.el-input__wrapper):hover {
  pointer-events: auto;
}

.no-auto-focus :deep(.el-date-editor) {
  pointer-events: none;
}

.no-auto-focus:hover :deep(.el-date-editor) {
  pointer-events: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .workload-management {
    padding: 16px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
}
</style>